import {Button, Col, Form, Input, Modal, Row, Select, Table, Tabs, TreeSelect} from 'antd';
import {connect} from 'umi';
import React, {useEffect, useState} from 'react';
import {findEmpByNameOrCode, findEmpByUserCodes, getDepartmentUser, getUserOrgById} from './service';
import { employeeStatusList } from '@/utils/constant';
import { findItemByTree } from '@/utils/functions';
import moment from 'moment';

const FormItem = Form.Item;
const { TabPane } = Tabs;

const formLayout = {
  labelCol: {span: 7},
};


/**
 *
 * @param handleOk  确认函数
 * @param handleCancel  取消函数
 * @param visible   是否显示
 * @param selectType  多选标记（ 0：单选，1：多选）
 * @param global  公司数据所在的object
 * @param isOrgGroupFilter 是否进行当前用户所在公司组过滤
 * @param showJobLevel 是否展示职级
 * @param currentUser 当前登录用户信息
 * @param isDismiss 是否查询离职人员
 * @returns {*}
 * @constructor
 */
const SelectUserModal = ({ handleOk, handleCancel, visible, selectType, isOrgGroupFilter = false, showJobLevel = true, global = {}, currentUser, isDismiss }) => {
  const {options = {}} = global;
  const {orgTree = [],jobLevel = []} = options;
  const [selectionType, setSelectionType] = useState('checkBox');
  const [selectMode, setSelectMode] = useState('tags');
  const [tabsKey, setTabsKey] = useState('1');
  const [usersInfo, setUsersInfo] = useState([]);
  const [userCodes, setUserCodes] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [userList,setUserList] = useState([]);
  const [dataTree, setDataTree] = useState([]);
  const [form1] = Form.useForm();
  const [form2] = Form.useForm();

  useEffect(() => {
    let localOrgTree =JSON.parse(JSON.stringify(orgTree));
    if (isOrgGroupFilter){
      let finalOrgTree = [];
      getUserOrgById(currentUser.id).then(res => {
        res.forEach(item => {
          finalOrgTree.push(findItemByTree(localOrgTree,parseInt(item)));
        });
        recursiveSetSelectable(finalOrgTree);
        setDataTree(finalOrgTree);
      })
    }else {
      recursiveSetSelectable(localOrgTree);
      setDataTree(localOrgTree);
    }
    setSelectionType(selectType === 0 ? 'radio' : 'checkBox');
    setSelectMode(selectType === 0 ? '' : 'multiple');
  }, [orgTree]);

  useEffect(()=>{
    if (visible){
      form1.resetFields();
      form2.resetFields();
      setTableData([]);
    }
  },[visible]);

  const recursiveSetSelectable = (list) =>{
    list.forEach(item => {
      if (item.children?.length>0)
        item.selectable = false;
      recursiveSetSelectable(item.children)
    })
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '公司',
      dataIndex: 'orgname',
    },
    {
      title: '部门',
      dataIndex: 'unitname',
    },
    {
      title: '职级',
      dataIndex: 'jobLevelId',
      hideInTable: !showJobLevel,
      render: (text) => {
        let target = jobLevel.find(item => (item.id === text));
        return text ? (target && showJobLevel) ? target.name : '' : ''
      }
    },
    {
      title: '入职时间',
      dataIndex: 'hiredate',
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    /*{
      title: '岗位',
      dataIndex: 'jobname',
    },*/
    {
      title: '状态',
      dataIndex: 'employeestatus',
      render: (text) =>{
        return text ? employeeStatusList.find(item => (item.value===text)).label : ''
      }
    }
  ];

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setUsersInfo(selectedRows);
    },
  };

  const onFinish = (values) => {
    values.isOrgGroupFilter = isOrgGroupFilter;
    values.isDismiss = isDismiss ? true : false;
    findEmpByNameOrCode(values).then(res => {
      setTableData(res);
    });
  };

  const onDepartmentChange = (value,node) =>{
    if(node.children.length < 1){
      getDepartmentUser(value,isDismiss).then((res) => {
        setUserList(res)
      })
    }
  };

  const onUserChange = (values) =>{
    setUserCodes(values);
  };

  const onTabChange = (activeKey) =>{
    setTabsKey(activeKey);
    if (selectType===0){
      if (activeKey==='1'){
        setUserCodes([]);
        form2.resetFields();
      }else {
        setUsersInfo([]);
        setTableData([]);
        form1.resetFields();
      }
    }
  };

  const confirm = () => {
    if (userCodes.length > 0){
      findEmpByUserCodes(userCodes).then(res =>{
        let finalUsersInfo = [...res];
        usersInfo.forEach(userByName =>{
          let isHad = false;
          res.forEach(userByDep =>{
            if (userByDep.code === userByName.code)
              isHad = true;
          });
          if (!isHad)
            finalUsersInfo.push(userByName);
        });
        // selectType===0 && handleOk(finalUsersInfo[0]);
        // selectType===1 && handleOk(finalUsersInfo);
        handleOk(finalUsersInfo);
        setUserCodes([]);
        setUsersInfo([]);
      })
    }else {
      // selectType===0 && handleOk(usersInfo[0]);
      // selectType===1 && handleOk(usersInfo);
      handleOk(usersInfo);
      setUsersInfo([]);
    }
  };

  const cancel = () => {
    handleCancel();
  };

  const getUserBySearchRender = () => (<>
      <Form {...formLayout} form={form1} onFinish={onFinish}>
        <Row gutter={24}>
          <Col span={9}>
            <FormItem name="name" label="姓名">
              <Input className='widthStyle'/>
            </FormItem>
          </Col>
          <Col span={9}>
            <FormItem name="code" label="工号">
              <Input className='widthStyle'/>
            </FormItem>
          </Col>
          <Col span={6}>
            <FormItem>
              <Button type="primary" htmlType="submit">搜索</Button>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <Table rowSelection={{type: selectionType, ...rowSelection}}
        rowKey='oid'
        columns={columns}
        dataSource={tableData}
      />
    </>
  );

  const getUserByDepartment = () => (
    <>
      <Form {...formLayout} form={form2} >
        <Row gutter={24} justify='center'>
          <Col span={16}>
            <FormItem labelAlign="left" labelCol={{span:4}} name="selectDepartment" label="选择部门">
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择人员部门"
                labelInValue={true}
                onSelect={(value,node) => onDepartmentChange(value,node)}
                treeData={dataTree}
              />
            </FormItem>
          </Col>
          <Col span={16}>
            <FormItem labelAlign="left" labelCol={{span:4}} name="users" label="选择人员">
              <Select mode={selectMode} placeholder="请选择人员" onChange={(value)=>onUserChange(value)} >
                { userList.length>0 ? userList.map((item, index) => {
                  return (
                    <Select.Option value={`${item.code}`} key={index}>{item.name}</Select.Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </>
  );

    return (
      <>
        <Modal maskClosable={false} title="选择人员" visible={visible} onOk={confirm} onCancel={cancel} width='70%'>
          <Tabs animated={false} defaultActiveKey="1" onChange={onTabChange}>
            <TabPane tab="通过查询信息选择" key="1">
              { getUserBySearchRender() }
            </TabPane>
            <TabPane tab="通过公司部门选择" key="2">
              { getUserByDepartment() }
            </TabPane>
          </Tabs>
        </Modal>
      </>
    );
};

export default connect(({ global, user }) => ({
  global,
  currentUser: user.currentUser,
}))(SelectUserModal)
